package org.leiyang.common.util;

import org.leiyang.common.dtos.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TokenUtil {
    private static final Logger log = LoggerFactory.getLogger(TokenUtil.class);

    /**
     * 生成AccessToken
     */
    public static String createAccessToken(String username, Long uid) {
        String content = uid + "@" + username + "@" + IdUtils.fastUUID();
        return CrpyUtil.encryptPBE(content);
    }

    /**
     * 从token里解析出用户信息
     */
    public static LoginUser parseToken(String token) {
        try {
            String content = CrpyUtil.decryptPBE(token);
            assert content != null;
            if (!content.contains("@")) {
                return null;
            }
            String[] data = content.split("@");
            return LoginUser.builder().token(token)
                    .username(data[1])
                    .userid(Long.parseLong(data[0]))
                    .build();
        } catch (Exception e) {
            log.error("解析token异常, ", e);
        }
        return null;
    }
}